package com.letv.so.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;
import org.apache.thrift.transport.TTransportException;

import com.letv.search.utils.ReflectionUtils;
import serving.ResultDocInfo;

/**
 * String工具类.<br>
 * 
 * 
 * 修改记录：<br>
 * 1.2010-03-29 djg 去除intern方法,避免内存溢出.<br>
 * 
 * @author djg
 * 
 */
public final class StringUtil extends StringUtils {

	private static final Logger logger = Logger.getLogger(StringUtil.class);

	public static final String zeroStr = "".intern();

	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");

	public static final String nullToZero(String str) {
		return str == null ? StringUtil.zeroStr : str;
	}

	/**
	 * @Title: blankToInit
	 * @Description: 空值赋值给初始化
	 * @param str
	 * @param init
	 * @return
	 * @return String
	 * @throws
	 */
	public static final String blankToInit(String str, String init) {
		if (StringUtils.isBlank(str)) {
			str = init;
		}
		return str;
	}

	public static final float blankToFloat(String str, float init) {

		return NumberUtils.toFloat(str, init);
	}

	public static final String format(String str) {
		if (str == null || str.trim().length() == 0) {
			return StringUtil.zeroStr;
		}
		return toHalfangle(str);
	}

	public static final String safeFormat(String str) {
		if (StringUtils.isBlank(str)) {
			return StringUtil.zeroStr;
		}
		StringBuilder sb = new StringBuilder();
		int len = str.length();
		char c;
		for (int i = 0; i < len; i++) {
			c = str.charAt(i);
			switch (c) {
			case '<':
				sb.append("&lt;");
				break;
			case '>':
				sb.append("&gt;");
				break;
			case '"':
				sb.append("&quot;");
				break;
			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}
	
	/**
	 * 判断是否为一个单位数字
	 * @param firstChar
	 * @return
	 */
	public static boolean isNumber(String intChar) {
		boolean isChar = intChar.matches("[0-9]");
		if (isChar) {
			return true;
		} else
			return false;
	}
	
	/**
	 * 判断是否为单一英文字符
	 * @param firstChar
	 * @return
	 */
	public static boolean isCharacter(String firstChar) {
		boolean isChar = firstChar.matches("[A-Za-z0-9]");
		if (isChar) {
			return true;
		} else
			return false;
	}
	
	/**
	 * 判断是否为英文字符
	 * @param firstChar
	 * @return
	 */
	public static boolean isCharacters(String chars) {
		boolean isChar = chars.matches("[A-Za-z0-9]+");
		if (isChar) {
			return true;
		} else
			return false;
	}

	/**
	 * 全角转半角
	 * 
	 */
	public static String toHalfangle(String src) {
		int len = src.length();
		StringBuilder sb = new StringBuilder();
		sb.ensureCapacity(len);
		char c;
		for (int i = 0; i < len; i++) {
			c = src.charAt(i);
			if (c > 65280 && c < 65375) {
				c -= 65248;
			} else if (c == 12288) {
				c = 32;
			}
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * 添加千分位分隔符
	 */
	public static final String formatQfw(int num) {
		if (num < 1000) {
			return String.valueOf(num);
		}
		StringBuilder sb = new StringBuilder();
		sb.append(num);
		String numStr = sb.reverse().toString();
		sb = new StringBuilder();
		for (int i = 0; i < numStr.length(); i++) {
			sb.append(numStr.charAt(i));
			if (i < numStr.length() - 1 && (i + 1) % 3 == 0) {
				sb.append(",");
			}
		}
		return sb.reverse().toString();
	}

	/**
	 * 字符串截取
	 * 
	 * @param key
	 * @param max
	 * @return
	 */
	public static final String substring(String key, int max, String elide) {
		if (key == null) {
			return StringUtil.zeroStr;
		}
		if (max == -1 || key.length() <= max) {
			return key;
		}
		StringBuilder sb = new StringBuilder();
		char[] charArr = key.toCharArray();
		int len = charArr.length;
		float l = 0;
		char ch;
		for (int i = 0; i < len; i++) {
			ch = charArr[i];
			if (Character.isDigit(ch) || Character.isSpaceChar(ch) || ch == '-' || (ch >= 'a' && ch <= 'z')) {
				l += 0.5;
			} else if (ch >= 'A' && ch <= 'Z') {
				l += 0.6;
			} else {
				l += 1.;
			}
			if (l >= max) {
				sb.append(elide);
				break;
			}
			sb.append(ch);
		}
		return sb.toString();
	}

	/**
	 * 格式化输出集数
	 * 
	 * @param num
	 * @param max
	 * @return
	 */
	public static final String fN(int num) {
		return num < 10 ? "0" + num : String.valueOf(num);
	}

	public static final boolean isLetterOrEmpty(String str) {
		if (str == null) {
			return false;
		}
		char c;
		for (int i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (!isLantingLetter(c) && !Character.isSpaceChar(c)) {
				return false;
			}
		}
		return true;
	}

	public static final boolean isLantingLetter(char ch) {
		return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z';
	}

	public static final String buildScoreHtml(float score, int voters) {
		if (score <= 0) {
			return "<span class=\"commet\">(0人评价)</span><span class=\"grade\"><font>0</font>.0分</span><span class=\"star\"><span style=\"width:0px\"></span></span>";
		}
		StringBuilder sb = new StringBuilder();
		sb.append("<span class=\"commet\">(").append(voters).append("人评价)</span>");
		int i = (int) score;
		int d = (int) ((score - i) * 10);
		sb.append("<span class=\"grade\"><font>").append(i).append("</font>");
		if (i < 10) {
			sb.append('.').append(d).append("分");
		}
		sb.append("</span><span class=\"star\"><span style=\"width:");
		sb.append(score * 6.8).append("px;\"></span></span>");
		return sb.toString();
	}

	public static final String buildScoreHtml(float score) {
		if (score <= 0) {
			return "<b>0</b>";
		}
		int i = (int) score;
		// int d = (int) ((score - i) * 10);
		BigDecimal b1 = new BigDecimal(Float.toString(score));
		BigDecimal b2 = new BigDecimal(Float.toString(i));
		float dd = b1.subtract(b2).floatValue();
		int d = (int) (dd * 10);
		return new StringBuilder("<i><b>").append(i).append("</b>").append('.').append(d).append("</i>").toString();
	}

	public static final String getTimeTip(long second) {
		int hour = (int) second / (60 * 60);
		int min = (int) (second - hour * 60 * 60) / 60;
		int sec = (int) second - min * 60 - hour * 60 * 60;
		StringBuilder sb = new StringBuilder();
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumIntegerDigits(2);
		nf.setMaximumFractionDigits(0);
		if (hour != 0) {
			sb.append(nf.format(hour)).append(':');
		}
		return sb.append(nf.format(min)).append(':').append(nf.format(sec)).toString();
	}

	public static final String strEncode(String src) {
		try {
			return URLEncoder.encode(src, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("key encode exception", e);
			return src;
		}
	}

	public static final String formatTime(String time) {
		try {
			return SDF.format(new Date(new Long(time)));
		} catch (Exception e) {
			logger.error("formatTime exception", e);
		}
		return "";
	}

	public static final String formatMMSSTime(String time) {
		try {
			int s = NumberUtil.getInt(time, 0);
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumIntegerDigits(2);
			nf.setMaximumFractionDigits(0);
			double f = Math.floor(s / 60);
			int d = (int) Math.floor(s % 60);
			return nf.format(f) + ":" + nf.format(d);
		} catch (Exception e) {
			logger.error("formatTime exception", e);
		}
		return "00:00";
	}
	/**
	 * 将字符串中的数字转成汉字
	 * @param l
	 * @return
	 */
	public static String changeCh(String l) {
		if(StringUtils.isBlank(l)){
			return "";
		}
		String[] ss = new String[100];
		for(int i=0; i<ss.length; i++) {
			ss[i] = "";
		}
		String str = "";
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("0", "零");
		hashMap.put("1", "一");
		hashMap.put("2", "二");
		hashMap.put("3", "三");
		hashMap.put("4", "四");
		hashMap.put("5", "五");
		hashMap.put("6", "六");
		hashMap.put("7", "七");
		hashMap.put("8", "八");
		hashMap.put("9", "九");
		int m = 0;
		for(int i=l.length()-1; i>=0; i--) {
			String cc = new Character(l.charAt(i)).toString();
			if(isNumber(cc)){
				if(m==0){
					ss[i] = hashMap.get(cc);
					m++;
				}else if(m==1){
					ss[i] = hashMap.get(cc) + "十";
					m++;
				}else if(m==2){
					ss[i] = hashMap.get(cc) + "百";
					m++;
				}else if(m==3){
					ss[i] = hashMap.get(cc) + "千";
					m++;
				}else if(m==3){
					ss[i] = hashMap.get(cc) + "万";
					m++;
				}
				str = ss[i] + str;
			}else{
				//str = cc+str;
				m=0;
			}
		}
		return str;
	}

	// public static final String getVideoByPush(AlbumBean4IPTV video) {
	// String str = "";
	// if (video.getVideocountByPush()!=null) {
	// int type = 0;
	// String url = video.getVideoUrl();
	// for ( Object key:video.getVideocountByPush().keySet()) {
	// type =Integer.parseInt( video.getVideocountByPush().get(key).toString());
	// url = url.replace("www.letv.com/ptv/pplay","yuanxian.letv.com/play");
	// }
	// if(type==7){
	// str = url+"";
	// }
	// }
	// return "";
	// }

	public static boolean isNotEmpty(String s) {
		return null != s && !s.equals("");
	}
	public static String converString(String [] arr, String conv){
		StringBuffer sb = new StringBuffer();
		if(arr != null && arr.length > 0){
			for(String s : arr){
				sb.append(s).append(conv);
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}
	public static ResultDocInfo byte2ResultDocInfo(byte[] bytes) {
	    logger.warn("Bytes lenth:"+bytes.length);
	    ResultDocInfo docInfo = new ResultDocInfo();
	    TMemoryBuffer memBuf = new TMemoryBuffer(bytes.length);
        try {
          memBuf.write(bytes);
        }catch (TTransportException e1) {
            logger.error("pars error,",e1);
        }
        TBinaryProtocol binProto = new TBinaryProtocol(memBuf);
        try {
            docInfo.read(binProto);
        }catch(Exception e) {
            logger.error("pars error,",e);
        }
	    return docInfo;
	}
	public static Object bytes2Entity(Class<?> entityClass,byte[] bytes) {
	      Object entity = null;
	      try {
	        entity = entityClass.newInstance();
	      }
	      catch (InstantiationException e1) {
	          logger.error("pars error,",e1);
	      }
	      catch (IllegalAccessException e1) {
	          logger.error("pars error,",e1);
	      }
	      TMemoryBuffer memBuf = new TMemoryBuffer(bytes.length);
	      try {
	        memBuf.write(bytes);
	      }
	      catch (TTransportException e1) {
	          logger.error("pars error,",e1);
	      }
	      TBinaryProtocol binProto = new TBinaryProtocol(memBuf);
	      try {
	        Method method = entity.getClass().getMethod("read", new Class[] { TProtocol.class });
	        method.invoke(entity, new Object[] { binProto });
	      }
	      catch (SecurityException e) {
	          logger.error("pars error,",e);
	      }
	      catch (NoSuchMethodException e) {
	          logger.error("pars error,",e);
	      }
	      catch (IllegalArgumentException e) {
	          logger.error("pars error,",e);
	      }
	      catch (IllegalAccessException e) {
	          logger.error("pars error,",e);
	      }
	      catch (InvocationTargetException e) {
	          logger.error("pars error,",e);
	      }
	      return entity;
	}
	public static void main(String[] arts) {
		System.out.println("zh_CN".toLowerCase());
//		System.out.println(NumberUtil.getInt(null, 0));
//		System.out.println(StringUtil.formatQfw(11111111));
//
//		int s = 2000;
//		DecimalFormat df = new DecimalFormat("#.##");
//		String result = df.format(2000);
//		System.out.println(result);
//		NumberFormat nf = NumberFormat.getInstance();
//		nf.setMinimumIntegerDigits(2);
//		nf.setMaximumFractionDigits(0);
//		double f = Math.floor(s / 60);
//		int d = (int) Math.floor(s % 60);
//
//		System.out.println(nf.format(f) + ":" + d);
//		System.out.println(StringUtil.buildScoreHtml(9.9f));
		System.out.println("lw".length());
	}
}
